<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { message } from 'ant-design-vue';
import type { TreeNode, TreeProps } from './types';

const props = withDefaults(defineProps<{
  treeData?: TreeNode[];
  selectedKeys?: string[];
  checkedKeys?: string[];
  checkable?: boolean;
  showIcon?: boolean;
  checkStrictly?: boolean;
  selectType?: string;
  loadData?: (node: any) => Promise<void>;
}>(), {
  treeData: () => [],
  selectedKeys: () => [],
  checkedKeys: () => [],
  checkable: true,
  showIcon: true,
  checkStrictly: false,
  selectType: 'default',
});

const emit = defineEmits<{
  (e: 'update:selectedKeys', keys: string[]): void;
  (e: 'update:checkedKeys', keys: string[]): void;
  (e: 'select', selectedKeys: string[], info: any): void;
  (e: 'check', checkedKeys: string[], info: any): void;
}>();

// 内部状态
const internalSelectedKeys = ref<string[]>(props.selectedKeys);
const internalCheckedKeys = ref<string[]>(props.checkedKeys);
const treeKey = ref(0);

// 监听外部属性变化
watch(() => props.selectedKeys, (newVal) => {
  internalSelectedKeys.value = newVal;
});

watch(() => props.checkedKeys, (newVal) => {
  internalCheckedKeys.value = newVal;
});

// 树节点选择事件
const onSelect = (selectedKeys: string[], info: any) => {
  internalSelectedKeys.value = selectedKeys;
  emit('update:selectedKeys', selectedKeys);
  emit('select', selectedKeys, info);
};

// 树节点勾选事件
const onCheck = (checkedKeys: string[], info: any) => {
  internalCheckedKeys.value = checkedKeys;
  emit('update:checkedKeys', checkedKeys);
  emit('check', checkedKeys, info);
};

// 加载数据
const onLoadData = async (treeNode: any) => {
  try {
    if (props.loadData) {
      await props.loadData(treeNode);
    }
  } catch (error) {
    console.error('Failed to load node data:', error);
    message.error('加载节点数据失败');
  }
};
</script>

<template>
  <div class="common-tree">
    <a-tree
      :key="treeKey"
      v-model:selected-keys="internalSelectedKeys"
      v-model:checked-keys="internalCheckedKeys"
      :tree-data="treeData"
      :checkable="checkable"
      :show-icon="showIcon"
      :check-strictly="checkStrictly"
      :load-data="onLoadData"
      @select="onSelect"
      @check="onCheck"
    >
      <template #icon v-if="showIcon">
        <IconifyIcon
          icon="cuida:building-outline"
          style="font-size: 20px"
        />
      </template>
    </a-tree>
  </div>
</template>

<style lang="scss" scoped>
.common-tree {
  :deep(.ant-tree-node-content-wrapper) {
    display: flex;
    align-items: center;
  }

  :deep(.ant-tree-icon__customize) {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
:deep(.customer-tree .tree-card){
  overflow: auto !important;
}
</style> 